package com.axzhengxin.platform.sync.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import com.axzhengxin.platform.sync.ISyncDataService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * SysUserRoleSyncServiceImpl
 *
 * @author jiangnan
 * @date 2021/3/25
 */
@Slf4j
@Service("syncUserRole")
public class SysUserRoleSyncServiceImpl implements ISyncDataService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    private static final Map<Long, Long> ROLE_MAPPER_CONVERT = MapUtil.<Long, Long>builder()
            .put(26L, 29L)
            .put(29L, 26L)
            .build();

    @SneakyThrows
    @Override
    public void exec() {
        exec2();
    }

    @SneakyThrows
    private void exec1() {
        String profile = SpringUtils.getActiveProfile();
        // 查询所有状态正常的机构，排除顶级机构企业征信中心
        List<SysUserRole> sourceDeptList = Db.use(DSFactory.get(profile))
                .find(Entity.create("sys_user_role"), SysUserRole.class)
                .stream()
                .filter(s -> 1L != s.getUserId())
                .collect(Collectors.toList());
        // 查询所有角色
        List<SysRole> sourceUserRoleList = Db.use(DSFactory.get(profile))
                .find(Entity.create("sys_role"), SysRole.class)
                .stream()
                .filter(r -> !"admin".equals(r.getRoleKey()))
                .filter(r -> !"common".equalsIgnoreCase(r.getRoleKey()))
                .collect(Collectors.toList());
        sysUserRoleMapper.batchUserRole(sourceDeptList);
        sourceUserRoleList.forEach(sysRoleMapper::insertRole);
    }

    @SneakyThrows
    private void exec2() {
        String profile = SpringUtils.getActiveProfile();
        // 查询所有状态正常的机构，排除顶级机构企业征信中心
        List<SysUserRole> sourceDeptList = Db.use(DSFactory.get(profile))
                .find(Entity.create("sys_user_role"), SysUserRole.class)
                .stream()
                .filter(ur -> 1L != ur.getUserId())
                .filter(ur -> 2L != ur.getRoleId())
                .peek(ur -> {
                    // 交换省总行普通管理员和客户经理的ROLE_ID，方便以最高权限进行统计
                    if (ROLE_MAPPER_CONVERT.containsKey(ur.getRoleId())) {
                        ur.setRoleId(ROLE_MAPPER_CONVERT.get(ur.getRoleId()));
                    }
                })
                .collect(Collectors.groupingBy(SysUserRole::getUserId))
                .values()
                .stream()
                .map(list -> list.stream().max(Comparator.comparingLong(SysUserRole::getRoleId)))
                .filter(Optional::isPresent)
                .map(Optional::get)
                .peek(ur -> {
                    // 交换省总行普通管理员和客户经理的ROLE_ID，转回原本的码值
                    if (ROLE_MAPPER_CONVERT.containsKey(ur.getRoleId())) {
                        ur.setRoleId(ROLE_MAPPER_CONVERT.get(ur.getRoleId()));
                    }
                })
                .filter(ur ->
                        isZero(sysRoleMapper.selectCountByUserIdAndRoleId(ur.getRoleId(), ur.getUserId()))
                )
                .collect(Collectors.toList());
        sysUserRoleMapper.batchUserRole(sourceDeptList);
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }

    public boolean isZero(int count){
        if ( count==0){
            return true;
        }
        return false;
    }
}
